﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using ClipboardHistory.Net.Utils;

namespace ClipboardHistory.Net
{
    public partial class Form1 : Form
    {
        #region interop clipboard
        [DllImport("User32.dll")]
        protected static extern bool AddClipboardFormatListener(int hwnd);

        [DllImport("User32.dll")]
        protected static extern bool RemoveClipboardFormatListener(int hwnd);

        [DllImport("User32.dll")]
        protected static extern int SetClipboardViewer(int hWndNewViewer);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        private IntPtr nextClipboardViewer;

        protected override void WndProc(ref Message m)
        {
            const int WM_CLIPBOARDUPDATE = 0x031D;
            const int WM_DRAWCLIPBOARD = 0x308;
            const int WM_CHANGECBCHAIN = 0x030D;

            switch (m.Msg)
            {
                case WM_CLIPBOARDUPDATE:
                    OnClipboardChanged();
                    break;

                case WM_DRAWCLIPBOARD:
                    OnClipboardChanged();
                    SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                case WM_CHANGECBCHAIN:
                    if (m.WParam == nextClipboardViewer)
                        nextClipboardViewer = m.LParam;
                    else
                        SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
                    break;

                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        #endregion

        public Form1()
        {
            InitializeComponent();
            try
            {
                AddClipboardFormatListener((int)this.Handle);
            }
            catch (EntryPointNotFoundException)
            {
                nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.Handle);
            }

            Hotkey hk = new Hotkey();
            hk.KeyCode = Keys.V;
            hk.Control = true;
            hk.Windows = true;
            hk.Pressed += new HandledEventHandler(hk_Pressed);
            if(hk.GetCanRegister(this))
            {
                hk.Register(this);
            }
        }

        void hk_Pressed(object sender, HandledEventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                Show();
                WindowState = FormWindowState.Normal;
            }
            else
            {
                Hide();
                WindowState = FormWindowState.Minimized;
            }
        }

        private void OnClipboardChanged()
        {
            try
            {
                if (Clipboard.ContainsAudio())
                {
                    //AddAudioItem();
                }
                else if (Clipboard.ContainsFileDropList())
                {
                    //AddFileDropListItem();
                }
                else if (Clipboard.ContainsImage())
                {
                    Image img = Clipboard.GetImage();

                    //AddImageItem();
                }
                else if (Clipboard.ContainsText())
                {
                    if (clipHistoryDataSet.ClipHistory.Select(string.Format("data = '{0}'", Clipboard.GetText())).Length == 0)
                    {
                        ClipHistoryDataSet.ClipHistoryRow newRow = clipHistoryDataSet.ClipHistory.NewClipHistoryRow();
                        newRow.textData = Clipboard.GetText();
                        newRow.dateAdded = DateTime.Now;
                        newRow.dataType = (int) ClipboardDataType.Text;
                        newRow.favorite = false;
                        clipHistoryDataSet.Clips.Rows.Add(newRow);
                        clipsTableAdapter.Update(clipHistoryDataSet.Clips);
                    }
                }
            }
            catch (Exception e1)
            {
                System.Diagnostics.Trace.Write(e1.ToString());
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;

        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                Hide();
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'clipHistoryDataSet.ClipHistory' table. You can move, or remove it, as needed.
            this.clipHistoryTableAdapter.Fill(this.clipHistoryDataSet.ClipHistory);
            // TODO: This line of code loads data into the 'clipHistoryDataSet.SearchHistory' table. You can move, or remove it, as needed.
            this.searchHistoryTableAdapter.Fill(this.clipHistoryDataSet.SearchHistory);

            comboBox1.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DoFilter(comboBox1.Text);
        }

        protected void DoFilter(string strFilter)
        {
            if(!string.IsNullOrEmpty(strFilter))
            {
                clipsBindingSource.Filter = string.Format("textdata LIKE '%{0}%'", strFilter);
                if(clipsBindingSource.Count > 0)
                {
                    if (clipHistoryDataSet.SearchHistory.Select(string.Format("searchquery = '{0}'", strFilter)).Length == 0)
                    {
                        //add filter to history
                        ClipHistoryDataSet.SearchHistoryRow newRow =
                            clipHistoryDataSet.SearchHistory.NewSearchHistoryRow();
                        newRow.searchquery = strFilter;
                        newRow.created = DateTime.Now;
                        clipHistoryDataSet.SearchHistory.Rows.Add(newRow);
                        searchHistoryTableAdapter.Update(clipHistoryDataSet.SearchHistory);
                        comboBox1.SelectedValue = strFilter;
                    }
                }
            }
            else
            {
                //clear filter
                clipsBindingSource.Filter = null;
            }
        }

        private void comboBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                DoFilter(comboBox1.Text);
            }
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var dataRow = (((DataRowView) clipsBindingSource[e.RowIndex]).Row as ClipHistoryDataSet.ClipHistoryRow);
                if (dataRow != null)
                {
                    switch ((ClipboardDataType) dataRow.dataType)
                    {
                        case ClipboardDataType.Text:
                            Clipboard.SetText(dataRow.textData);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch(Exception ex)
            {
                
            }
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            
        }
    }
}
